/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.table;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.je.auth.check.annotation.AuthCheckPermission;
import com.je.common.base.DynaBean;
import com.je.common.base.exception.APIWarnException;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.CommonCheckService;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.cache.table.TableCache;
import com.je.meta.rpc.develop.DevelopLogRpcService;
import com.je.meta.service.SystemColumnTypeEnum;
import com.je.meta.service.table.MetaTableColumnService;
import com.je.meta.service.table.MetaTableService;
import com.je.meta.service.table.MetaTableTraceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.*;

/**
 * 资源表列管理
 */
@RestController
@RequestMapping(value = "/je/meta/resourceTable/table/column")
public class TableColumnController extends AbstractPlatformController {

    @Autowired
    private MetaTableColumnService metaTableColumnService;
    @Autowired
    private MetaTableTraceService metaTableTraceService;
    @Autowired
    private MetaTableService tableService;
    @Autowired
    private CommonCheckService commonCheckService;
    @Autowired
    private TableCache tableCache;
    @Autowired
    private DevelopLogRpcService developLogRpcService;
    @Autowired
    private MetaService metaService;
    @Autowired
    private Environment environment;


    /**
     * 批量导出表结构
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = {"/exportColumns"}, method = {RequestMethod.GET}, produces = {"application/json; charset=utf-8"})
    public File exportColumns(BaseMethodArgument param, HttpServletRequest request) {
        String defaultDirectory = environment.getProperty("servicecomb.downloads.directory");
        String fileName = getStringParameter(request,"fileName");
        String tableCodes = getStringParameter(request,"tableCodes");
        String type = getStringParameter(request,"type");
        String title = StringUtil.isEmpty(getStringParameter(request,"title"))?"系统表结构信息":getStringParameter(request,"title");
        InputStream inputStream =metaTableColumnService.exportColumns(title,type,tableCodes);
        FileUtil.writeFromStream(inputStream, defaultDirectory + File.separator + fileName);
        return new File(defaultDirectory + File.separator + fileName);
    }

    /**
     * 添加列
     *
     * @param param
     * @param request
     * @return
     */
    @Override
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = {"/doSave"}, method = {RequestMethod.POST}, produces = {"application/json; charset=utf-8"})
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        try {
            DynaBean dynaBean = new DynaBean("JE_CORE_TABLECOLUMN", true);
            String resourceCode = getStringParameter(request, "RESOURCETABLE_TABLECODE");
            String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
            String orderIndex = String.valueOf(findColumnCount(resourceId));
            if (StringUtil.isEmpty(resourceCode)) {
                return BaseRespResult.errorResult(MessageUtils.getMessage("table.code.canotEmpty"));
            }
            if (StringUtil.isEmpty(resourceId)) {
                return BaseRespResult.errorResult(MessageUtils.getMessage("table.id.canotEmpty"));
            }
            if (StringUtil.isEmpty(orderIndex)) {
                return BaseRespResult.errorResult(MessageUtils.getMessage("table.orderIndex.canNotEmpty"));
            }
            dynaBean.setStr("TABLECOLUMN_RESOURCETABLE_ID", resourceId);
            dynaBean.setStr("TABLECOLUMN_TABLECODE", resourceCode);
            dynaBean.setStr("SY_ORDERINDEX", orderIndex);
            dynaBean.setStr("TABLECOLUMN_TYPE", "VARCHAR100");
            dynaBean.set("TABLECOLUMN_ISNULL", "1");
            dynaBean.setStr("TABLECOLUMN_CLASSIFY", "PRO");
            dynaBean.set("TABLECOLUMN_UNIQUE", 0);
            dynaBean.set("TABLECOLUMN_ISCREATE", 0);
            dynaBean.setStr("TABLECOLUMN_TREETYPE", "NORMAL");
            request.setAttribute("dynaBean", dynaBean);
            HashMap<String, Object> values = this.manager.doSave(param, request).getValues();
            return BaseRespResult.successResult(values, MessageUtils.getMessage("common.add.success"));
        } catch (PlatformException var4) {
            throw var4;
        } catch (Exception var5) {
            throw new PlatformException(MessageUtils.getMessage("common.save.error"), PlatformExceptionEnum.UNKOWN_ERROR, var5);
        }
    }

    /**
     * 移除列
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doDelete", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult removeColumn(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String tablecolumnTablecode = getStringParameter(request, "TABLECOLUMN_TABLECODE");
        if (StringUtil.isEmpty(tablecolumnTablecode)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("column.code.notEmpty"));
        }
        tableCache.clear();
        dynaBean.set("TABLECOLUMN_TABLECODE", tablecolumnTablecode);
        String ids = param.getIds();

        String result = metaTableColumnService.checkTypeById(ids);
        if (StringUtil.isNotEmpty(result)) {
            return BaseRespResult.errorResult(result);
        }
        boolean isExist = metaTableColumnService.checkIsExistForeignKeyByColumnIds(ids);
        metaTableColumnService.removeColumn(dynaBean, ids, true);
        DynaBean table = metaService.selectOne("JE_CORE_RESOURCETABLE",ConditionsWrapper.builder().eq("RESOURCETABLE_TABLECODE",tablecolumnTablecode));
        developLogRpcService.doDevelopLog("COLUMN_DELETE", "删除字段", "TABLE", "资源表", dynaBean.getStr("TABLECOLUMN_NAME"), dynaBean.getStr("TABLECOLUMN_CODE"), dynaBean.getStr("JE_CORE_TABLECOLUMN_ID"),table.getStr("SY_PRODUCT_ID"));
        return BaseRespResult.successResult(isExist?"refresh":"1000", "", MessageUtils.getMessage("common.delete.success"));
    }

    /**
     * 增加字段
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addField", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult addField(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String funcinfoId = getStringParameter(request, "FUNCINFO_ID");
        if (StringUtil.isEmpty(funcinfoId)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.id.canNotEmpty"));
        }
        if(StringUtil.isEmpty(dynaBean.getStr("TABLECOLUMN_CODE"))){
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.params.canotEmpty","TABLECOLUMN_CODE"));
        }
        dynaBean.setStr("funcinfoId", funcinfoId);
        String result =  metaTableColumnService.addField(dynaBean);
        if(StringUtil.isNotEmpty(result)){
            return BaseRespResult.errorResult(result);
        }
        return BaseRespResult.successResult(MessageUtils.getMessage("common.save.success"));
    }

    /**
     * 导入列
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/impNewCols", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult impNewCols(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        metaTableColumnService.impNewCols(dynaBean);
        return BaseRespResult.successResult(null, MessageUtils.getMessage("common.import.success"));
    }

    /**
     * 字段校验
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/checkUnique", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult checkUnique(BaseMethodArgument param, HttpServletRequest request) {
        String ids = getStringParameter(request, "addColumnCodes");
        String pkValue = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
        String tableCode = getStringParameter(request, "tableCode");
        if (StringUtil.isEmpty(ids)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.fieldCheck.fieldEmpty"));
        }
        if (StringUtil.isEmpty(pkValue)&&StringUtil.isEmpty(tableCode)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.fieldCheck.tableEmpty"));
        }
        if(StringUtil.isNotEmpty(tableCode)){
           DynaBean dynaBean = metaService.selectOne("JE_CORE_RESOURCETABLE",ConditionsWrapper.builder().eq("RESOURCETABLE_TABLECODE",tableCode));
            pkValue = dynaBean.getStr("JE_CORE_RESOURCETABLE_ID");
        }

        String result = metaTableColumnService.checkUnique(ids, pkValue);
        if (StringUtil.isNotEmpty(result)) {
            return BaseRespResult.errorResult("201", result.split(","), MessageUtils.getMessage("table.column.code.multi", result));
        }
        return BaseRespResult.successResult("1000", "", MessageUtils.getMessage("table.saveAuxiliary.success"));
    }

    /**
     * 初始化系统字段
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addSystemColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult addSystemColumn(BaseMethodArgument param, HttpServletRequest request) {
        String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", resourceId);
        if (table != null) {
            try {
                boolean status = metaTableColumnService.addSystemColumn(request);
                if (!status) {
                    return BaseRespResult.errorResult(MessageUtils.getMessage("common.add.error"));
                }
            } catch (APIWarnException e) {
                return BaseRespResult.errorResult(e.getCode(), e.getMessage());
            }
        }

        String type = getStringParameter(request, "type");
        if (SystemColumnTypeEnum.CREATE.getName().equals(type)) {
            return BaseRespResult.successResult(type, MessageUtils.getMessage("table.column.saveAddColumn"));
        } else if (SystemColumnTypeEnum.UPDATE.getName().equals(type)) {
            return BaseRespResult.successResult(type, MessageUtils.getMessage("table.column.updateAddColumn"));
        } else if (SystemColumnTypeEnum.WORKFLOW_EXTEND.getName().equals(type)) {
            return BaseRespResult.successResult(type, MessageUtils.getMessage("table.column.workAddColumn"));
        } else if (SystemColumnTypeEnum.WORKFLOW_BASE.getName().equals(type)) {
            return BaseRespResult.successResult(type, MessageUtils.getMessage("table.column.workAddColumn"));
        } else if (SystemColumnTypeEnum.EXTEND.getName().equals(type)) {
            return BaseRespResult.successResult(type, MessageUtils.getMessage("table.column.extendAddColumn"));
        } else if (SystemColumnTypeEnum.PRODUCT.getName().equals(type)) {
            return BaseRespResult.successResult(type, MessageUtils.getMessage("table.column.productAddColumn"));
        } else {
            return BaseRespResult.successResult(type, MessageUtils.getMessage("table.column.system"));
        }

    }

    /**
     * 根据字典添加字段
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addAuxiliaryDdColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult addColumnByDD(BaseMethodArgument param, HttpServletRequest request) {
        try {
            String ddCode = getStringParameter(request, "ddCode");
            if (StringUtil.isEmpty(ddCode)) {
                return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("dictionary.code.canNotEmpty"));
            }
            DynaBean dynaBean = new DynaBean("JE_CORE_TABLECOLUMN", true);
            dynaBean.setStr("ddCode", ddCode);
            dynaBean.setStr("JE_CORE_RESOURCETABLE_ID", getStringParameter(request, "JE_CORE_RESOURCETABLE_ID"));
            dynaBean.setStr("addColumnCodes", getStringParameter(request, "addColumnCodes"));
            dynaBean.setStr("ddName",getStringParameter(request,"ddName"));
            String result = metaTableColumnService.addColumnByDD(dynaBean);
            if (StringUtil.isNotEmpty(result)) {
                return BaseRespResult.errorResult(result);
            }
            String isApply = getStringParameter(request, "isApply");
            if ("1".equals(isApply)) {
                String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
                tableService.updateTable(resourceId, true);
            }
            return BaseRespResult.successResult("1000", "", MessageUtils.getMessage("table.saveAuxiliary.success"));
        } catch (PlatformException pe) {
            return BaseRespResult.errorResult(pe.getErrorMsg());
        } catch (Exception e) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("common.add.error"));
        }

    }

    /**
     * 根据级联字典添加字段
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addAuxiliaryCasacdeDdColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult addColumnByDDList(BaseMethodArgument param, HttpServletRequest request) {
        String strData = getStringParameter(request, "strData");
        String pkValue = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
        String whereSql = getStringParameter(request, "whereSql");
        if (StringUtil.isEmpty(strData)) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("dictionary.canNotEmpty"));
        }
        if (StringUtil.isEmpty(pkValue)) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("table.id.canotEmpty"));
        }
        DynaBean dynaBean = new DynaBean();
        dynaBean.setStr("strData", strData);
        dynaBean.setStr("JE_CORE_RESOURCETABLE_ID", pkValue);
        dynaBean.setStr("whereSql", whereSql);
        String result = metaTableColumnService.addColumnByDDList(dynaBean);
        if (StringUtil.isNotEmpty(result)) {
            return BaseRespResult.errorResult(result);
        }
        String isApply = getStringParameter(request, "isApply");
        if ("1".equals(isApply)) {
            String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
            tableService.updateTable(resourceId, true);
        }

        return BaseRespResult.successResult("1000", "", MessageUtils.getMessage("table.saveAuxiliary.success"));
    }

    /**
     * 根据表加字段
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addAuxiliaryTableColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult addColumnByTable(BaseMethodArgument param, HttpServletRequest request) {
        String strData = param.getStrData();
        String pkValue = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
        String createchild = getStringParameter(request, "CREATECHILD");
        String isApply = getStringParameter(request, "isApply");
        String FUNCCODE = getStringParameter(request, "FUNCCODE");
        String queryStr = getStringParameter(request, "queryStr");
        if (StringUtil.isEmpty(pkValue)) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("table.id.canotEmpty"));
        }
        if (StringUtil.isEmpty(createchild)) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("column.isHaveForeign"));
        }

        if (StringUtil.isNotEmpty(strData) && StringUtil.isNotEmpty(pkValue)) {
            DynaBean dynaBean = new DynaBean();
            dynaBean.setStr("strData", strData);
            dynaBean.setStr("JE_CORE_RESOURCETABLE_ID", pkValue);
            dynaBean.setStr("CREATECHILD", createchild);
            dynaBean.setStr("FUNCCODE", FUNCCODE);
            dynaBean.setStr("queryStr", queryStr);
            String result = metaTableColumnService.addColumnByTable(dynaBean);
            if (StringUtil.isNotEmpty(result)) {
                return BaseRespResult.errorResult(result);
            }
            if ("1".equals(isApply)) {
                String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
                tableService.updateTable(resourceId, true);
            }
            return BaseRespResult.successResult("1000", "", MessageUtils.getMessage("table.saveAuxiliary.success"));
        } else {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("common.params.illegal"));
        }
    }

    /**
     * 根据表加字段
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addAuxiliaryUserColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult addAuxiliaryUserColumn(BaseMethodArgument param, HttpServletRequest request) {
        String strData = param.getStrData();
        String pkValue = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
        String tableCode = getStringParameter(request, "tableCode");
        String queryStr = getStringParameter(request, "queryStr");
        String createchild = getStringParameter(request, "CREATECHILD");
        String funccode = getStringParameter(request, "FUNCCODE");
        String isApply = getStringParameter(request, "isApply");
        if (StringUtil.isEmpty(strData)) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("column.dictionary.canNotEmpyt"));
        }
        if (StringUtil.isEmpty(pkValue)) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("table.id.canotEmpty"));
        }
        if (StringUtil.isEmpty(tableCode)) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("table.code.canotEmpty"));
        }
        if (StringUtil.isEmpty(queryStr)) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("common.query.canNotEmpty"));
        }
        if (StringUtil.isEmpty(createchild)) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("column.isHaveForeign"));
        }
        if (StringUtil.isEmpty(funccode)) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("column.spec.userFunc.canNotEmpty"));
        }
        DynaBean dynaBean = new DynaBean();
        dynaBean.setStr("strData", strData);
        dynaBean.setStr("JE_CORE_RESOURCETABLE_ID", pkValue);
        dynaBean.setStr("tableCode", tableCode);
        dynaBean.setStr("queryStr", queryStr);
        dynaBean.setStr("CREATECHILD", createchild);
        dynaBean.setStr("FUNCCODE", funccode);
        String result = metaTableColumnService.addColumnByTable(dynaBean);
        if (StringUtil.isNotEmpty(result)) {
            return BaseRespResult.errorResult(result);
        }
        if ("1".equals(isApply)) {
            String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
            tableService.updateTable(resourceId, true);
        }
        return BaseRespResult.successResult("1000", "", MessageUtils.getMessage("table.saveAuxiliary.success"));
    }

    /**
     * 根据原子加列
     */
    @Deprecated
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addColumnByAtom", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult addColumnByAtom(BaseMethodArgument param) {
        String strData = param.getStrData();
        String pkValue = param.getPkValue();
        String tableCode = param.getTableCode();
        if (StringUtil.isNotEmpty(strData) && StringUtil.isNotEmpty(pkValue)) {
            Integer count = metaTableColumnService.addColumnByAtom(strData, tableCode, pkValue);
            return BaseRespResult.successResult(MessageUtils.getMessage("column.addedNum", count));
        } else {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.params.illegal"));
        }
    }

    /**
     * 存为原子列
     */
    @Deprecated
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addAtomByColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult addAtomByColumn(BaseMethodArgument param, HttpServletRequest request) {
        String strData = param.getStrData();
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        if (StringUtil.isNotEmpty(strData) && StringUtil.isNotEmpty(dynaBean.getStr("ATOMCOLUMN_ATOM_ID"))) {
            metaTableColumnService.addAtomByColumn(strData, dynaBean.getStr("ATOMCOLUMN_ATOM_ID"));
            return BaseRespResult.successResult(MessageUtils.getMessage("common.import.success"));
        } else {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.params.illegal"));
        }
    }

    /**
     * 添加新增相关字段
     */
    @Deprecated
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/generateCreateInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult generateCreateInfo(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        if (StringUtil.isNotEmpty(dynaBean.getStr("TABLECOLUMN_RESOURCETABLE_ID"))) {
            DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", dynaBean.getStr("TABLECOLUMN_RESOURCETABLE_ID"));
            Long count = metaService.countBySql(ConditionsWrapper.builder()
                    .table("JE_CORE_TABLECOLUMN")
                    .eq("TABLECOLUMN_CODE", "SY_CREATETIME")
                    .eq("TABLECOLUMN_RESOURCETABLE_ID", dynaBean.getStr("TABLECOLUMN_RESOURCETABLE_ID")));
            if (count > 0) {
                return BaseRespResult.errorResult(MessageUtils.getMessage("column.exits"));
            } else {
                try {
                    boolean status = metaTableColumnService.initCreateColumns(table);
                    if (!status) {
                        return BaseRespResult.errorResult(MessageUtils.getMessage("common.save.error"));
                    }
                } catch (APIWarnException e) {
                    return BaseRespResult.errorResult(e.getCode(), e.getMessage());
                }
            }
        } else {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.params.illegal"));
        }
        return BaseRespResult.successResult(MessageUtils.getMessage("table.generate.saveFiled"));
    }

    /**
     * @param param
     */
    @Deprecated
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/generateUpdateInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult generateUpdateInfo(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        if (StringUtil.isNotEmpty(dynaBean.getStr("TABLECOLUMN_RESOURCETABLE_ID"))) {
            DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", dynaBean.getStr("TABLECOLUMN_RESOURCETABLE_ID"));
            Long count = metaService.countBySql(ConditionsWrapper.builder()
                    .table("JE_CORE_TABLECOLUMN")
                    .eq("TABLECOLUMN_CODE", "SY_MODIFYTIME")
                    .eq("TABLECOLUMN_RESOURCETABLE_ID", dynaBean.getStr("TABLECOLUMN_RESOURCETABLE_ID")));
            if (count > 0) {
                return BaseRespResult.errorResult(MessageUtils.getMessage("column.exits"));
            } else {
                try {
                    boolean status = metaTableColumnService.initUpdateColumns(table);
                    if (!status) {
                        return BaseRespResult.errorResult(MessageUtils.getMessage("common.save.error"));
                    }
                } catch (APIWarnException e) {
                    return BaseRespResult.errorResult(e.getCode(), e.getMessage());
                }
            }
        } else {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.params.illegal"));
        }
        return BaseRespResult.successResult(MessageUtils.getMessage("table.generate.updateFiled"));
    }

    /**
     * @param param
     */
    @Deprecated
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/generateShInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult generateShInfo(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        if (StringUtil.isNotEmpty(dynaBean.getStr("TABLECOLUMN_RESOURCETABLE_ID"))) {
            DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", dynaBean.getStr("TABLECOLUMN_RESOURCETABLE_ID"));
            Long count = metaService.countBySql(ConditionsWrapper.builder()
                    .table("JE_CORE_TABLECOLUMN")
                    .eq("TABLECOLUMN_CODE", "SY_ACKFLAG")
                    .eq("TABLECOLUMN_RESOURCETABLE_ID", dynaBean.getStr("TABLECOLUMN_RESOURCETABLE_ID")));
            if (count > 0) {
                return BaseRespResult.errorResult(MessageUtils.getMessage("column.exits"));
            } else {
                metaTableColumnService.initShColumns(table);
                return BaseRespResult.successResult(MessageUtils.getMessage("column.exits"));
            }
        } else {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.params.illegal"));
        }
    }

    //    /**
//     * 获取业务字典的个数
//     */
//    @RequestMapping(value = "/findColumnCount", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
//    @ResponseBody
    public int findColumnCount(String tableCodeId) {
        int count = 1;
        List<Map<String, Object>> countInfos = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) ORDERINDEX FROM JE_CORE_TABLECOLUMN WHERE SY_ORDERINDEX is not null and TABLECOLUMN_CLASSIFY={0} AND TABLECOLUMN_RESOURCETABLE_ID={1}", "PRO", tableCodeId);
        if (countInfos != null && countInfos.size() > 0 && countInfos.get(0) != null) {
            String countStr = countInfos.get(0).get("ORDERINDEX") + "";
            if (StringUtil.isNotEmpty(countStr)) {
                count = Integer.parseInt(countStr) + 1;
            }
        }
        return count;
    }

    /**
     * 更新多条记录
     *
     * @param param
     */
    @Override
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdateList(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String strData = param.getStrData();
        if (StringUtil.isEmpty(strData)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.strData.canNotEmpty"));
        }
        String result = metaTableColumnService.checkStrData(strData);
        if (StringUtil.isNotEmpty(result)) {
            return BaseRespResult.errorResult(result);
        }
        String isVarLength = checkDoUpdateListByTypeIsVarLength(strData);
        if (!StringUtil.isEmpty(isVarLength)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("column.spec.length"));
        }
        int count = 0;
        try {
            count = metaTableColumnService.doUpdateListByColumn(dynaBean, strData);
        } catch (APIWarnException e) {
            return BaseRespResult.errorResult(e.getCode(), e.getMessage());
        }
        return BaseRespResult.successResult("", MessageUtils.getMessage("common.save.success"));
    }

    private String checkDoUpdateListByTypeIsVarLength(String strData) {
        JSONArray data = JSONArray.parseArray(strData);
        for (Object obj : data) {
            JSONObject item = JSONObject.parseObject(String.valueOf(obj));
            if ("VARCHAR".equals(item.getString("TABLECOLUMN_TYPE"))) {
                String length = item.getString("TABLECOLUMN_LENGTH");
                if (StringUtil.isEmpty(length)) {
                    return item.getString("TABLECOLUMN_NAME");
                }
            }
        }
        return null;

    }
}
